#pragma once
#include <iostream>
#include <string>
#include "Protocol.hpp"

enum
{
    Div_Zero = 1,
    Mod_Zero,
    Other_Oper
};

class Calculator
{
public:
    Calculator(){}
    ~Calculator(){}
public:
    // "len"\n"10 + 20"\n"
    std::string Handler(std::string &package)
    {
        std::string content;
        // 1. 提取有报文的效载荷
        bool r = Decode(package, &content);
        if (!r) {
            return "";
        }
        // 2. 将报文的有效载荷反序列化, 并存入Request中
        Request req;
        r = req.Deserialize(content);
        if (!r) {
            return "";
        }
        content = "";
        // 3. 计算
        Response resp = CalculatorHelper(req);
        // 4. 将结果序列化
        resp.Serialize(&content);
        // 5. 将有效载荷添加添加报头
        content = Encode(content);
        return content;
    }
    // 计算
    Response CalculatorHelper(const Request &req)
    {
        Response resp(0, 0);
        switch (req.op)
        {
        case '+':  resp.result = req.x + req.y;  break;       
        case '-':  resp.result = req.x - req.y;  break;
        case '*':  resp.result = req.x * req.y;  break;
        case '/':
            {
                if (req.y == 0)  resp.code = Div_Zero;
                else  resp.result = req.x / req.y;
                break;
            } 
        case '%':
            {
                if (req.y == 0)  resp.code = Mod_Zero;
                else  resp.result = req.x % req.y;
                break;
            } 
        default:  resp.code = Other_Oper; break;
        }
        return resp;
    } 
};

